﻿using System.Linq;
using Microsoft.Practices.Composite.Modularity;

namespace PrismNavigationFramework.Infrastructure
{
    public class LoadedModulesRegistrationService : ILoadedModulesRegistrationService
    {
        private readonly IModuleNamesRegistrationService _moduleNamesRegistrationService;
        private readonly IModuleCatalog _moduleCatalog;

        public LoadedModulesRegistrationService(IModuleNamesRegistrationService moduleNamesRegistrationService, IModuleCatalog moduleCatalog)
        {
            _moduleNamesRegistrationService = moduleNamesRegistrationService;
            _moduleCatalog = moduleCatalog;
        }


        public bool ModuleIsLoaded(string moduleName)
        {
            var realModuleName = this._moduleNamesRegistrationService.GetRealModuleName(moduleName);

            if (string.IsNullOrEmpty(realModuleName))
            {
                realModuleName = moduleName;
            }

            return this._moduleCatalog.Modules.Any(
                p => p.ModuleName == realModuleName && p.State == ModuleState.Initialized);
        }
    }
}